package com.spring.team_propaganda_system.controller;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.team_propaganda_system.dao.ArticleDao;
import com.spring.team_propaganda_system.dao.ClassificationDao;
import com.spring.team_propaganda_system.entity.Article;
import com.spring.team_propaganda_system.entity.Classification;
import com.spring.team_propaganda_system.entity.User;
import com.spring.team_propaganda_system.utils.JwtToken;
import com.spring.team_propaganda_system.utils.MyUtil;
import com.spring.team_propaganda_system.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@Controller
@RequestMapping("/articleController")
@Api(value = "ArticleController", description = "文章相关api")
@Transactional
public class ArticleController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    private ArticleDao articleDao;
    @Autowired(required = false)
    private ClassificationDao classificationDao;

    /**
     * 添加文章
     * @param article
     * @param multipartFile
     * @param request
     * @param Authorization
     * @return
     * @throws IOException
     * @throws TokenExpiredException
     */
    @ApiOperation("添加文章")
    @ApiImplicitParam(name = "article",value = "article信息",required = true,dataType = "Article")
    @PostMapping("/web/addArticle")
    @ResponseBody
    public ResponseEntity addArticle(
//                                           @RequestParam(required = true) String article_name,
//                                            @RequestBody(required = true) String article_content,
//                                            @RequestParam(required = true) String user_name,
//                                            @RequestParam(required = false) String classification_name,
            @RequestBody Article article,
                                            @RequestParam(required = true) MultipartFile multipartFile,
                                            HttpServletRequest request,
                                            @RequestHeader String Authorization) throws IOException, TokenExpiredException {
        ResponseEntity responseEntity;
        String token = Authorization;
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User user = JwtToken.unsign(token, User.class);
        //用户角色，分微信用户和老师用户，1代表微信用户，2代表老师用户,默认为微信用户
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        //根据user_jobNumber查询数据库是否有该用户存在，不存在则注册，存在则注册失败
//        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("article_id", article_id);
//        Article article = articleDao.selectOne(queryWrapper);
//        //User userFromBase = userDao.selectById(user_name);
//        if (article == null){
            //图片资源访问路径
            String fileLocation = "/static/restaurantRes/";
            //获取提交文件名称
            String filename = multipartFile.getOriginalFilename();
            String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

            //定义上传文件存放的路径
            String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
            System.out.println(path);
            //返回保存的url，根据url可以进行文件查看或者下载
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() //端口 https443端口无需添加
                    + fileLocation + newfilename;

            String ariticle_picture = filePath;//根路径+文件名
            File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
            multipartFile.transferTo(file);
            responseEntity = ResponseEntity.ok();
            Article article1 = new Article();
            article1.setArticle_name(article.getArticle_name());
            article1.setArticle_content(article.getArticle_content());
            article1.setClassification_name(article.getClassification_name());
            article1.setUser_name(article.getUser_name());
            article1.setArticle_picture(ariticle_picture);
            articleDao.insert(article1);
            responseEntity.putDataValue("article_id",article1.getArticle_id());
            responseEntity.putDataValue("msg","文章添加成功");
            return responseEntity;
//        }else {
////            responseEntity = ResponseEntity.badRequest();
////            responseEntity.putDataValue("msg","文章添加失败");
////        }
////        return responseEntity;
    }

    /**
     * 修改文章信息
     * @param article_id
     * @param classification_name
     * @param article_name
     * @param article_content
     * @param user_name
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("修改文章信息")
    @PutMapping("/web/updateArticle")
    @ResponseBody
    public ResponseEntity updateArticle(@RequestParam(required = true) int article_id,
                                               @RequestParam(required = false) String classification_name,
                                               @RequestParam(required = false) String article_name,
                                               @RequestParam(required = false) String article_content,
                                               @RequestParam(required = false) String user_name,
                                               @RequestHeader String Authorization,
                                        @RequestParam(required = true) MultipartFile multipartFile,
                                        HttpServletRequest request) throws IOException {
        ResponseEntity responseEntity;
        String token = Authorization;
        if (flag =myUtil.judgeToken(token)) {
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg", "token不存在或已过期");
            return responseEntity;
        }
        User users = JwtToken.unsign(token, User.class);
        if (users == null) {
            responseEntity = ResponseEntity.notFound();
            responseEntity.putDataValue("msg", "用户不存在");
            return responseEntity;
        } else if (users.getUser_role()!=2) {
            responseEntity = ResponseEntity.unauthorized();
            responseEntity.putDataValue("msg", "没有权限");
            return responseEntity;

        } else {
            //图片资源访问路径
            String fileLocation = "/static/restaurantRes/";
            //获取提交文件名称
            String filename = multipartFile.getOriginalFilename();
            String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

            //定义上传文件存放的路径
            String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
            System.out.println(path);
            //返回保存的url，根据url可以进行文件查看或者下载
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() //端口 https443端口无需添加
                    + fileLocation + newfilename;

            String ariticle_picture = filePath;//根路径+文件名
            File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
            multipartFile.transferTo(file);
            responseEntity = ResponseEntity.ok();
            Article article = articleDao.selectById(article_id);
            article.setUser_name(user_name);
            article.setClassification_name(classification_name);
            article.setArticle_content(article_content);
            article.setArticle_name(article_name);
            article.setArticle_picture(ariticle_picture);
            articleDao.updateById(article);
            responseEntity.putDataValue("msg", "文章修改成功");
            return responseEntity;
        }
    }

    /**
     * 根据article_id查询文章信息
     * @param article_id
     * @return
     * @throws IOException
     */
    @ApiOperation("根据article_id查询文章信息")
    @PutMapping("/web/selectByArticleId")
    @ResponseBody
    public ResponseEntity selectByArticleId(@RequestParam(required = true) Integer article_id) throws IOException {
        ResponseEntity responseEntity;
        responseEntity=ResponseEntity.ok();
        int is_delete = 0;
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", is_delete);
        queryWrapper.eq("article_id", article_id);
        Article article=articleDao.selectOne(queryWrapper);
        responseEntity.putDataValue("article",article);
        return responseEntity;

    }
    /**
     * 根据classification_name查询文章信息
     * @param classification_name
     * @return
     * @throws IOException
     */
    @ApiOperation("根据classification_name查询文章信息")
    @PutMapping("/web/selectByClassificatioName")
    @ResponseBody
    public ResponseEntity selectByClassificatioName(@RequestParam(required = true) String classification_name) throws IOException {
        ResponseEntity responseEntity;
            QueryWrapper<Article> wrapper = new QueryWrapper<>();
            int is_delete=0;
            wrapper.eq("is_delete", is_delete) ;
            wrapper.eq("classification_name",classification_name);
            List<Article> list = articleDao.selectList(wrapper);
            responseEntity=ResponseEntity.ok();
            responseEntity.putDataValue("article",list);
            return responseEntity;
    }
    /**
     * 返回主分类的文章
     * @return
     * @throws IOException
     */
    @ApiOperation("返回主分类的文章")
    @PutMapping("/web/selectByClassificationid")
    @ResponseBody
    public ResponseEntity selectByClassificationid() throws IOException {
        ResponseEntity responseEntity;
        Integer classification_id = 1;
        Classification classification = classificationDao.selectById(classification_id);
        String classification_name = classification.getClassification_name();
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("classification_name",classification_name);
        List<Article> list = articleDao.selectList(wrapper);
        responseEntity=ResponseEntity.ok();
        responseEntity.putDataValue("article",list);
        return responseEntity;
    }

    /**
     * 根据id删除文章信息
     * @param article_id
     * @param Authorization
     * @return
     * @throws IOException
     */
    @ApiOperation("根据id删除文章信息")
    @PutMapping("/web/deleteArticle")
    @ResponseBody
    public ResponseEntity deleteArticle(@RequestParam(required = true) Integer article_id,
                                        @RequestHeader String Authorization)throws IOException{
        ResponseEntity responseEntity;
        String token=Authorization;
        if(flag=myUtil.judgeToken(token)){
            responseEntity=ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        User users=JwtToken.unsign(token,User.class);
        if(users==null){
            responseEntity=ResponseEntity.notFound();
            responseEntity.putDataValue("msg","用户不存在");
            return responseEntity;
        }else if(users.getUser_role()==2) {
            Article article = articleDao.selectById(article_id);
            if(article!=null){
                int is_delete=1;
                article.setIs_delete(is_delete);
                String classification_name = "";
                article.setClassification_name(classification_name);
                articleDao.updateById(article);

                responseEntity=ResponseEntity.ok();
                responseEntity.putDataValue("msg","删除成功");
                return responseEntity;
            }
        }
        responseEntity=ResponseEntity.unauthorized();
        responseEntity.putDataValue("msg","没有权限");
        return responseEntity;
    }
    /**
     * 文章列表
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("文章列表")
    @PostMapping("/web/ArticleList")
    @ResponseBody
    public ResponseEntity ArticleList(
                                             HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseData;
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
//        int is_delete=0;
//        wrapper.eq("is_delete", is_delete);
        List<Article> list = articleDao.selectList(wrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("article",list);
        responseData.putDataValue("msg","成功");
        return responseData;
    }
    /**
     * 统计文章数量
     */
    @ApiOperation("统计文章数量")
    @GetMapping("/web/count")
    @ResponseBody
    public ResponseEntity count() throws IOException {
        ResponseEntity responseData;
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        int  count =articleDao.selectCount(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("count", count);
        return responseData;
    }


}
